package com.unitechs.controller.lock;

import com.unitechs.commons.utils.ZyucLockUtils;

public class LockTestMain {
    private static int sharedNumber = 0;

    public static void main(String[] args) {
        //synchronizedStr();
        synchronizedLock();
    }



    static void synchronizedLock(){
        // 创建两个线程，共享同一个资源
        Thread thread1 = new Thread(new MyRunnableLock());
        Thread thread2 = new Thread(new MyRunnableLock());

        // 启动两个线程
        thread1.start();
        thread2.start();
    }



    static void synchronizedStr(){
        // 创建两个线程，共享同一个资源
        Thread thread1 = new Thread(new MyRunnable());
        Thread thread2 = new Thread(new MyRunnable());

        // 启动两个线程
        thread1.start();
        thread2.start();
    }

    static class MyRunnable implements Runnable {
        String code=new String("RD00001");

        public void run() {
            for (int i = 0; i < 5; i++) {
                // 使用synchronized确保线程安全
                synchronized (code) {
                    // 操作共享资源
                    sharedNumber++;
                    System.out.println(Thread.currentThread().getName() + ": " + sharedNumber);
                }

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }



    // 定义一个Runnable实现
    static class MyRunnableLock implements Runnable {
        String code=new String("RD00001");

        public void run() {
            for (int i = 0; i < 5; i++) {
                //code就是字符串
               ZyucLockUtils.zyucExecuteWithLock(code,()->{
                   //这里写需要进行线程管控的任务
                   sharedNumber++;
                   System.out.println(Thread.currentThread().getName() + ": " + sharedNumber);

               });

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
